package com.tecode.controller;



import com.tecode.bean.Admin;
import com.tecode.config.GetWeekTime;
import com.tecode.config.Time;
import com.tecode.service.AdminService;
import com.tecode.service.UserService;
import com.tecode.service.song.SongService;
import com.tecode.util.Md5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/4/2.
 */
@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private SongService songService;
    @Autowired
    private UserService userService;
    @Autowired
    private GetWeekTime getWeekTime;


    /**
     *
     * 获取欢迎页面数据
     */
    @RequestMapping("/welcome.html")
    public String toWelcome(Model model) throws ParseException, IOException {
        Integer musicAllNum=0;

        Integer dayMusicNum=0;
        Integer monthMusicNum=0;
        Integer weekMusicNum=0;
        Integer dayUserNum=0;
        Integer monthUserNum=0;
        Integer weekUserNum=0;

        Integer dayVisitNum=0;
        Integer monthVisitNum=0;
        Integer weekVisitNum=0;
        Date min;
        Date max;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//day
        SimpleDateFormat mf = new SimpleDateFormat("yyyy-MM");//month

        Time time = new Time();
        time.setDayTime(df.format(new Date()));
        time.setMonthTime(mf.format(new Date()));
        time.setWeekTime(getWeekTime.getTimeInterval(new Date()));

        min = df.parse(time.getWeekTime().split(",")[0]);
        max = df.parse(time.getWeekTime().split(",")[1]);

        List<Map> music = songService.getList();
        List<Map> user = userService.getUserCreateTime();
        List<Map> access = userService.selectAllAccess();

        //统计音乐各时间段
        for (int i=0; i<music.size(); i++){
            if(music.get(i).containsKey("auditTime") && ((Integer)music.get(i).get("cid") == 10)){
                musicAllNum++;
                if ((music.get(i).get("auditTime").toString()).equals(time.getDayTime())){
                    dayMusicNum++;
                }

                if ((music.get(i).get("auditTime").toString()).substring(0,7).equals(time.getMonthTime())){
                    monthMusicNum++;
                }

                Date d = (Date) music.get(i).get("auditTime");
                if(min.getTime()<=d.getTime() && d.getTime()<max.getTime()){
                    weekMusicNum++;
                }
            }
        }

        //统计用户各时间段
        for (int i=0; i<user.size(); i++){
            if (user.get(i).get("createtime").toString().equals(time.getDayTime())){
                dayUserNum++;
            }

            if(user.get(i).get("createtime").toString().substring(0,7).equals(time.getMonthTime())){
                monthUserNum++;
            }

            Date d = (Date) user.get(i).get("createtime");
            if(min.getTime()<=d.getTime() && d.getTime()<max.getTime()){
                weekUserNum++;
            }
        }

        for (int i=0; i<access.size(); i++){
            if(access.get(i).get("access_time").toString().equals(time.getDayTime())){
                dayVisitNum++;
            }

            if (access.get(i).get("access_time").toString().substring(0,7).equals(time.getMonthTime())){
                monthVisitNum++;
            }

            Date d = (Date) access.get(i).get("access_time");
            if(min.getTime()<=d.getTime() && d.getTime()<max.getTime()){
                weekVisitNum++;
            }
        }

        model.addAttribute("userNotice",userService.selectUserByTypeId());
        model.addAttribute("musicNotice",userService.selectMusicByCId());

        model.addAttribute("weekMusic",weekMusicNum);
        model.addAttribute("weekUser",weekUserNum);
        model.addAttribute("weekVisit",weekVisitNum);

        model.addAttribute("monthMusic",monthMusicNum);
        model.addAttribute("monthUser",monthUserNum);
        model.addAttribute("monthVisit",monthVisitNum);

        model.addAttribute("allMusic",musicAllNum);
        model.addAttribute("allUser",user.size());
        model.addAttribute("allVisit",access.size());

        model.addAttribute("dayMusic",dayMusicNum);
        model.addAttribute("dayUser",dayUserNum);
        model.addAttribute("dayVisit",dayVisitNum);

        return "welcome.html";
    }


    /**
     * 用户登录
     * @param adminname
     * @param password
     * @param map
     * @param session
     * @return
     */
    @RequestMapping("/loginIn")
    public String adminLogin(String adminname,String password,Map<String,Object> map,HttpSession session) {
        String error="";
        if (StringUtils.isBlank(adminname)||StringUtils.isBlank(password)) {
            error = "账号或密码不能为空";
        }
        Admin admin=adminService.adminLogin(adminname);
        if (admin==null){
            error="账号错误";
        }else if (!admin.getPassword().equals(Md5Util.getStrMD5(password.trim()))) {
            error="密码错误";
        }
        else if (admin.getFreeze()==1) {
            error="账号未启用";
        }

        else if (admin.getPassword().equals(Md5Util.getStrMD5(password.trim()))){
            session.setAttribute("admin",admin);
            return "redirect:/index/html";
        }
        map.put("error",error);
            return "login";
    }

    /**
     * 管理员列表展示
     * @param map
     * @return
     */
    @RequestMapping("/admin-list")
    public String adminList(Map<String,Object> map){
       map.put("adminList",adminService.getAdminAll());
        return "admin-list" ;
    }

    /**
     * 管理员信息添加
     * @param adminName
     * @param password
     * @param adminRole
     * @return
     */
    @RequestMapping("/adminadd")
    @ResponseBody
    public Integer adminadd(String adminName,String password,int adminRole){
        if (adminService.adminLogin(adminName)!=null){
            return -1;
        }
        String pwd= Md5Util.getStrMD5(password);
        Integer integer=adminService.adminadd(adminName,pwd,adminRole);
        return integer;
    }

    /**
     * 进入管理员添加界面
     * @return
     */
    @RequestMapping("/addHtml")
    public String addHtml(){
        return "admin-add";
    }

    /**
     * 进入管理员信息修改界面
     * @param adminid
     * @param map
     * @return
     */
    @RequestMapping("/updateHtml/{id}")
    public String updateHtml(@PathVariable("id")int adminid ,Map<String,Object> map){
        Admin admin=adminService.adminSerch(adminid);
       map.put("adminUpdate",admin);
        return "admin-add";
    }

    /**
     * 进入权限修改界面
     * @param adminid
     * @param map
     * @return
     */
    @RequestMapping("/updatePermission/{id}")
    public String updatePermission(@PathVariable("id")int adminid ,Map<String,Object> map){
        Admin admin=adminService.adminSerch(adminid);
        map.put("adminUpdate",admin);
        return "admin-role";
    }

    /**
     * 管理员信息修改
     * @param adminName
     * @param password
     * @param adminRole
     * @param adminid
     * @return
     */
    @RequestMapping("/adminUpdate")
    @ResponseBody
    public Integer adminUpdate(String adminName,String password,int adminRole,int adminid){
        String pwd= Md5Util.getStrMD5(password);
        Integer integer= adminService.adminUpdate(adminName,pwd,adminRole,adminid);
        return integer;
    }
    @RequestMapping("/Permission")
    @ResponseBody
    public Integer updatePermission(String adminName,int adminRole,int adminid){
        Integer integer= adminService.updatePermission(adminid,adminRole,adminName);
        return integer;
    }

    /**
     * 删除和批量删除
     * @param list
     * @return
     */
    @RequestMapping(value = "/delete/all/{List}")
    public String deletAll(@PathVariable(value ="List") Integer[] list) {

          adminService.deletAll(list);
        return "redirect:/admin-list";
    }

    /**
     * 按名称查询
     * @param serch
     * @param map
     * @return
     */
    @RequestMapping(value = "/serch/all/{rows}")
    public String serchAll(@PathVariable(value ="rows") String serch ,Map<String,Object> map) {
        serch="%"+serch+"%";
        map.put("adminList",adminService.serchAll(serch));
        return "admin-list";
    }

    /**
     * 停用账号
     * @param id
     * @return
     */
    @RequestMapping("/upDate/freeze/{id}")
    public String freeze(@PathVariable(value = "id")int id){
       adminService.freeze(id);
        return "redirect:/admin-list";
    }

    /**
     * 启用账号
     * @param id
     * @return
     */
    @RequestMapping("/upDate/freeze2/{id}")
    public String freeze2(@PathVariable(value = "id")int id){
        adminService.freeze2(id);
        return "redirect:/admin-list";
    }

    /**
     * 进入权限信息界面
     * @return
     */
    @RequestMapping(value = "/admin-permission")
    public String permission() {
        return "admin-permission";
    }
    /**
     * 进入登录界面
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.setAttribute("admin",null);
        return "redirect:/login.page";
    }

}
